package cn.tedu.sgs.user.controller;

import cn.tedu.sgs.base.response.JsonResult;
import cn.tedu.sgs.base.response.StatusCode;
import cn.tedu.sgs.user.mapper.UserMapper;
import cn.tedu.sgs.user.pojo.dto.*;
import cn.tedu.sgs.user.pojo.entity.User;
import cn.tedu.sgs.user.pojo.vo.UserVO;
import cn.tedu.sgs.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/v1/user")
public class UserController {
	@Autowired
	UserService userService;

	@PostMapping("login")
	//@RequestBody注解，将前端传过来的值一一映射到DTO对象属性上
	public JsonResult login(@RequestBody UserLoginParam userLoginParam){
		log.debug("用户登录:userLoginParam={}",userLoginParam);
		UserVO userVO = userService.login(userLoginParam);
		// 权限验证,如果用户已有身份是user但选择了admin身份，则返回权限不足
		if ("user".equals(userVO.getRole()) && "admin".equals(userLoginParam.getRole())) {
			return JsonResult.ok(StatusCode.ACCESS_DENIED);
		}
		 // 权限验证,如果用户已有身份是admin但选择了user身份，足则返回权限有误
		if ("admin".equals(userVO.getRole()) && "user".equals(userLoginParam.getRole())) {
			return JsonResult.ok(StatusCode.ACCESS_ERROR);
		}
		return JsonResult.ok(userVO);
	}

	@PostMapping("reg")
	public JsonResult reg(@RequestBody UserRegParam userRegParam){
		log.debug("用户注册:UserRegParam={}",userRegParam);
		userService.reg(userRegParam);
		return JsonResult.ok(StatusCode.REGISTER_SUCCESS);
	}

	@GetMapping("select")
	public JsonResult selectUser(UserQuery userQuery) {
		log.debug("查询用户:userQuery={}",userQuery);
		List<UserVO> list = userService.selectUser(userQuery);
		return JsonResult.ok(list);
	}


	@PostMapping("changePassword")
	public JsonResult changePassword(@RequestBody UserChangePasswordParam userChangePasswordParam) {
		log.debug("修改密码: userChangePasswordParam={}", userChangePasswordParam);
		userService.changePassword(userChangePasswordParam);
		return JsonResult.ok();
	}

	@PostMapping("save")
	public JsonResult saveUser(UserSaveParam userSaveParam) {
		log.debug("保存用户:userSaveParam={}",userSaveParam);
		userService.saveUser(userSaveParam);
		return JsonResult.ok();
	}

	@PostMapping("/update/password/{userId}")
	public JsonResult resetPassword(@PathVariable Long userId){
		log.debug("重置密码:{}",userId);
		userService.resetPassword(userId);
		return JsonResult.ok();
	}

	@PostMapping("delete/{userId}")
	public JsonResult deleteUser(@PathVariable Long userId){
		log.debug("删除用户:{}",userId);
		userService.deleteUser(userId);
		return JsonResult.ok();
	}

	@PostMapping("savePoints")
	public JsonResult savePoints(UserUpdateParam userUpdateParam){
		log.debug("保存积分:{}",userUpdateParam);
		userService.savePoints(userUpdateParam);
		return JsonResult.ok();
	}
}
